iT邦幫忙

2024 iThome 鐵人賽

DAY 9
0
Odoo

30天就算 0 基礎,也能使用 GenAI 創造簡單的 Odoo 模組應用系列 第 9

【Day09】 物件導向構建電商系統:Class、繼承與封裝的應用

  • 分享至 

  • xImage
  •  

https://ithelp.ithome.com.tw/upload/images/20240923/20163326pZqfC5MQx0.png

商品管理 (Class 與 init 方法)

在電商系統中,商品(Product)是核心物件。我們可以用 class 來定義每個商品,並用 init 來初始化商品屬性。Product 類別表示電商中的一個商品,而 init 方法則初始化商品的名稱、價格和庫存。

class Product:
    def __init__(self, name, price, stock):
        self.name = name
        self.price = price
        self.stock = stock

# 創建商品實例
product1 = Product("Laptop", 1500, 10)
print(product1.name)  # Output: Laptop
print(product1.price)  # Output: 1500

購物車計算總價 (Method 方法)

在電商系統中,購物車會包含多個商品,並需要計算總價。可以定義一個方法來計算購物車中的商品總價。定義了 ShoppingCart 類別,並使用 calculate_total 方法來計算購物車中的總價。

class ShoppingCart:
    def __init__(self):
        self.items = []

    def add_item(self, product, quantity):
        self.items.append({'product': product, 'quantity': quantity})

    def calculate_total(self):
        total = 0
        for item in self.items:
            total += item['product'].price * item['quantity']
        return total

# 創建購物車實例
cart = ShoppingCart()
cart.add_item(product1, 2)
print(cart.calculate_total())  # Output: 3000

不同類型的商品 (Inheritance 繼承)

在電商系統中,商品可能有不同的類型,如實體商品(PhysicalProduct)和數字商品(DigitalProduct)。我們可以用繼承來實現這種商品類型的差異。PhysicalProduct 和 DigitalProduct 繼承了 Product 類別,並且加入了各自特有的屬性(如重量和文件大小)。

class PhysicalProduct(Product):
    def __init__(self, name, price, stock, weight):
        super().__init__(name, price, stock)
        self.weight = weight

class DigitalProduct(Product):
    def __init__(self, name, price, stock, file_size):
        super().__init__(name, price, stock)
        self.file_size = file_size

# 創建不同類型的商品
laptop = PhysicalProduct("Laptop", 1500, 10, 2.5)  # 2.5kg
ebook = DigitalProduct("Ebook", 20, 100, 50)  # 50MB

顧客資料保護 (Encapsulation 封裝)

電商系統中,顧客的敏感資訊(如信用卡資料)應該被封裝,避免外部直接訪問。客的信用卡資訊被封裝為私有屬性,僅能透過方法 get_credit_card_last_digits 來取得後四碼,保護敏感資料的隱私性。

class Customer:
    def __init__(self, name, email, credit_card):
        self.name = name
        self.email = email
        self.__credit_card = credit_card  # 封裝信用卡資訊

    def get_credit_card_last_digits(self):
        return self.__credit_card[-4:]

# 創建顧客實例
customer = Customer("Alice", "alice@example.com", "1234567890123456")

# 嘗試直接訪問信用卡資訊(失敗)
print(customer.__credit_card)  # AttributeError: 'Customer' object has no attribute '__credit_card'

# 使用方法取得信用卡後四碼
print(customer.get_credit_card_last_digits())  # Output: 3456


上一篇
【Day08】函數設計 (function):自動化報表輸出和客戶資料管理
下一篇
【Day10】模組 (Module) 化設計及使用:稅務計算功能為例
系列文
30天就算 0 基礎,也能使用 GenAI 創造簡單的 Odoo 模組應用21
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言